import json
import logging
from typing import Dict, Any, List
from sqlalchemy.orm import Session
from app.models.database import UserProfile, InteractionRecord, ModelUsageStats
from app.database.crud import get_db

class UserProfileService:
    """用户画像服务"""
    
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.db = next(get_db())
    
    def update_user_profile(self, user_id: str, interaction_data: Dict[str, Any]):
        """更新用户画像"""
        try:
            # 获取或创建用户画像
            profile = self.db.query(UserProfile).filter(UserProfile.user_id == user_id).first()
            if not profile:
                profile = UserProfile(user_id=user_id, username=f"user_{user_id}")
                self.db.add(profile)
            
            # 更新使用统计
            self._update_usage_stats(profile, interaction_data)
            
            # 更新偏好模型
            self._update_preferred_models(profile, interaction_data)
            
            self.db.commit()
            self.logger.info(f"用户画像已更新: {user_id}")
            
        except Exception as e:
            self.db.rollback()
            self.logger.error(f"更新用户画像失败: {str(e)}")
    
    def _update_usage_stats(self, profile: UserProfile, data: Dict[str, Any]):
        """更新使用统计"""
        stats = profile.usage_stats or {}
        
        # 更新模型使用次数
        model_used = data.get('model_used')
        if model_used:
            model_stats = stats.get('model_usage', {})
            model_stats[model_used] = model_stats.get(model_used, 0) + 1
            stats['model_usage'] = model_stats
        
        # 更新总使用次数
        stats['total_interactions'] = stats.get('total_interactions', 0) + 1
        stats['last_activity'] = data.get('timestamp')
        
        profile.usage_stats = stats
    
    def _update_preferred_models(self, profile: UserProfile, data: Dict[str, Any]):
        """更新偏好模型"""
        model_used = data.get('model_used')
        feedback = data.get('user_feedback', 0)
        
        if not model_used:
            return
        
        preferred_models = profile.preferred_models or []
        
        # 如果是正面反馈，提升模型优先级
        if feedback == 1:
            if model_used in preferred_models:
                preferred_models.remove(model_used)
            preferred_models.insert(0, model_used)
        # 如果是负面反馈，降低模型优先级
        elif feedback == -1 and model_used in preferred_models:
            preferred_models.remove(model_used)
            preferred_models.append(model_used)
        
        # 保持列表长度
        if len(preferred_models) > 5:
            preferred_models = preferred_models[:5]
        
        profile.preferred_models = preferred_models
    
    def get_user_recommendation(self, user_id: str, intent_type: str) -> str:
        """获取用户模型推荐"""
        profile = self.db.query(UserProfile).filter(UserProfile.user_id == user_id).first()
        
        if profile and profile.preferred_models:
            # 优先返回用户偏好的模型
            return profile.preferred_models[0]
        
        # 默认推荐逻辑
        default_recommendations = {
            'multimodal': 'Qwen3-Omni-7B',
            'reasoning': 'DeepSeek-R1-7B',
            'long_document': 'Llama3-8B-128K',
            'coding': 'DeepSeek-Coder-6.7B'
        }
        
        return default_recommendations.get(intent_type, 'DeepSeek-R1-7B')
    
    def get_user_stats(self, user_id: str) -> Dict[str, Any]:
        """获取用户统计信息"""
        profile = self.db.query(UserProfile).filter(UserProfile.user_id == user_id).first()
        if not profile:
            return {}
        
        # 计算最近活动
        recent_interactions = self.db.query(InteractionRecord).filter(
            InteractionRecord.user_id == user_id
        ).order_by(InteractionRecord.created_at.desc()).limit(10).all()
        
        return {
            'user_id': user_id,
            'preferred_models': profile.preferred_models or [],
            'total_interactions': profile.usage_stats.get('total_interactions', 0) if profile.usage_stats else 0,
            'model_usage': profile.usage_stats.get('model_usage', {}) if profile.usage_stats else {},
            'recent_activity': [
                {
                    'input': interaction.user_input[:100] + '...' if len(interaction.user_input) > 100 else interaction.user_input,
                    'model': interaction.model_used,
                    'time': interaction.created_at.isoformat()
                }
                for interaction in recent_interactions
            ]
        }